package cn.micai.base.io;

import java.io.File;
import java.io.FilenameFilter;

/**
 * 描述：如何找到具有特定扩展的文件
 * <p>
 *
 * @author: 赵新国
 * @date: 2018/6/20 15:04
 */
public class FindCertainExtension {

    private static final String FILE_DIR = "D://test";
    private static final String FILE_TEXT_EXT = ".txt";

    public static void main(String [] args) {

        new FindCertainExtension().listFile(FILE_DIR, FILE_TEXT_EXT);

    }

    public void listFile(String folder, String ext) {
        GenericExtFilter filter = new GenericExtFilter(ext);

        File dir = new File(folder);

        if (!dir.isDirectory()) {
            System.out.println("Directory does not exists : " + FILE_DIR);
            return;
        }

        // list out all the file name and filter by the extension
        String[] list = dir.list(filter);

        if (list.length == 0) {
            System.out.println("no files end with : " + ext);
            return;
        }

        for (String file : list) {
            String temp = new StringBuffer(FILE_DIR).append(File.separator).append(file).toString();
            System.out.println("file: " + temp);
        }


    }

    // inner class, generic extension filter 内部类，通用扩展过滤器
    public class GenericExtFilter implements FilenameFilter {
        private String ext;

        public GenericExtFilter(String ext) {
            this.ext = ext;
        }

        @Override
        public boolean accept(File dir, String name) {
            return (name.endsWith(ext));
        }
    }
}
